import logging
from termcolor import colored

# 自定义日志处理器
class ColoredFormatter(logging.Formatter):
    def format(self, record):
        # 根据日志级别选择颜色
        if record.levelno == logging.INFO:
            level_color = 'cyan'
        elif record.levelno == logging.WARNING:
            level_color = 'yellow'
        elif record.levelno == logging.ERROR:
            level_color = 'red'
        elif record.levelno == logging.DEBUG:
            level_color = 'blue'
        elif record.levelno == logging.CRITICAL:
            level_color = 'magenta'
        else:
            level_color = 'white'
        
        # 添加颜色到日志级别
        record.levelname = colored(record.levelname, level_color)

        # 格式化消息和时间戳
        message = super().format(record)
        return message

# 配置日志记录器
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()

# 设置处理器使用自定义格式化
formatter = ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', 
                            datefmt='%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)

# 添加处理器到记录器
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

# 示例日志
def log_example():
    logger.debug("This is a debug message.")
    logger.info("This is an info message.")
    logger.warning("This is a warning message.")
    logger.error("This is an error message.")
    logger.critical("This is a critical message.")

# 测试
if __name__ == "__main__":
    log_example()